<template>
  <el-card>
    <el-form
      class="container_header"
      :inline="true"
      label-width="80px"
      style="height: 34px"
    >
      <el-form-item label="用户名：">
        <el-input placeholder="请输入搜索用户名" v-model="userName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :disabled="userName.trim() === ''"
          @click="searchUser"
        >
          搜索
        </el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="primary" @click="addFlag">添加用户</el-button>
    <el-button
      type="danger"
      @click="batchDelete"
      :disabled="selectionArr.length > 0 ? false : true"
    >
      批量删除
    </el-button>
    <el-table
      @selection-change="handleSelectionChange"
      v-model:data="userList"
      style="width: 100%; margin: 10px 0"
      border
    >
      <el-table-column
        align="center"
        width="40px"
        type="selection"
      ></el-table-column>
      <el-table-column
        align="center"
        label="#"
        type="index"
        width="50px"
      ></el-table-column>
      <el-table-column
        align="center"
        label="ID"
        width="100px"
        prop="id"
      ></el-table-column>
      <el-table-column
        align="center"
        label="用户名字"
        prop="username"
      ></el-table-column>
      <el-table-column
        align="center"
        label="用户名称"
        prop="name"
      ></el-table-column>
      <el-table-column
        align="center"
        label="用户角色"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        align="center"
        label="更新时间"
        prop="updateTime"
      ></el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="assginFlag(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="editUser(row)"
          >
            编辑
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Delete"
            @click="deleteUser(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="getUserList"
      @current-change="getUserList"
      :background="true"
      v-model:current-page="currentPage"
      :page-sizes="[5, 7, 9, 11]"
      v-model:page-size="pageSize"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
    ></el-pagination>
  </el-card>

  <!-- 此处错误：:visible="drawer"  v-model:visible="drawer"  :visible.sync="drawer" 都无法正常显示-->
  <!-- 具名插槽本身有定位作用  #header 等同于 v-slot:"header" -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ addUserParams.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form
        :rules="addUserRules"
        ref="addUserForm"
        :model="addUserParams"
        label-width="80px"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input
            v-model="addUserParams.name"
            placeholder="请输入用户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="username">
          <el-input
            v-model="addUserParams.username"
            placeholder="请输入用户昵称"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-show="addUserParams.id ? false : true"
          label="用户密码"
          prop="password"
        >
          <el-input
            v-model="addUserParams.password"
            placeholder="请输入用户密码"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="demo-drawer__footer">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateUser">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <el-drawer v-model="drawerRole">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form ref="asignRolesForm" :model="addUserParams">
        <el-form-item label="用户姓名">
          <el-input v-model="addUserParams.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <!-- <el-checkbox-group> -->
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            label="全选"
            @change="handleCheckAllChange"
          ></el-checkbox>
          <!-- </el-checkbox-group> -->
          <el-checkbox-group
            v-model="assignRolesList"
            @change="handleCheckedChange"
          >
            <!-- 遍历展示 -->
            <!-- 此处收集的是 lable -->
            <el-checkbox
              v-for="(item, index) in allRolesList"
              :label="item"
              :key="item.id"
              name="roleName"
            >
              {{ item.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="demo-drawer__footer">
        <el-button @click="drawerRole = false">取消</el-button>
        <el-button type="primary" @click="assignRoles">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqAddOrUpdUser,
  reqAllUser,
  reqAssginRoles,
  reqBatchDeleteUser,
  reqDeleteUser,
  reqRolesList,
} from '../../../api/acl/user'
import {
  UserResponseData,
  Records,
  User,
  ResponseGetAllRoles,
} from '../../../api/acl/user/type'
import { ElMessage } from 'element-plus'
import useLayoutStore from '@/store/modules/layout'
let layoutStore = useLayoutStore()
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)
let userList = ref<Records>([]) // reactive 与 ref 方法有什么区别 为啥用 reactive　此处数据刷新会延迟
// let userList = reactive<Records>([])  // reactive 与 ref 方法有什么区别 为啥用 reactive　此处数据刷新会延迟
let userName = ref<string>('')
let drawer = ref<boolean>(false)
let isIndeterminate = ref<boolean>(true)
let checkAll = ref<boolean>(false)
let drawerRole = ref<boolean>(false)
let selectionArr = ref<any>([])
let allRolesList = ref<any>([])
let assignRolesList = ref<any>([])
// let asignRolesParams = reactive<any>({
//   username: '',
//   roleName: '',
//   userId: 0,
//   roleIdList: [],
// })
let addUserParams = reactive<User>({
  id: 0,
  name: '',
  username: '',
  password: '',
})
const addUserForm = ref()
const getUserList = async (page = 1) => {
  currentPage.value = page
  let res: UserResponseData = await reqAllUser(
    currentPage.value,
    pageSize.value,
  )
  console.log(res)
  if (res.code === 200) {
    total.value = res.data.total
    userList.value = res.data.records
  }
}
// const changeSize = () => {
//   getUserList()
// }
// const changePage = (page: number) => {
//   // console.log(page);
//   // console.log(currentPage.value);
//   getUserList(page)
// }
// 分配角色
const assginFlag = async (row: any) => {
  Object.assign(addUserParams, row)
  // 获取所有角色列表
  // id 怎么取  用户 id
  let res: ResponseGetAllRoles = await reqRolesList(addUserParams.id as number)
  console.log(res)
  if (res.code === 200) {
    allRolesList.value = res.data.allRolesList
    assignRolesList.value = res.data.assignRoles
    drawerRole.value = true
  }
}
// 如何体现选中关系
const handleCheckedChange = (value: any) => {
  //   console.log(value)
  //   console.log(assignRolesList.value);
  checkAll.value = assignRolesList.value.length === allRolesList.value.length
  isIndeterminate.value =
    assignRolesList.value.length > 0 &&
    assignRolesList.value.length < allRolesList.value.length
}
// 如何实现全选功能
const handleCheckAllChange = (value: any) => {
  assignRolesList.value = value ? allRolesList.value : []
  isIndeterminate.value = false
}

const assignRoles = async () => {
  // let roleIdList: number[] = []
  // assignRolesList.value.length > 0 &&
  //   assignRolesList.value.forEach((element: any) => {
  //     roleIdList.push(element.id)
  //   })
  // map 使用
  let dataRole = {
    userId: addUserParams.id as number,
    roleIdList: assignRolesList.value.map((item: any) => {
      return item.id as number
    }),
  }
  let res = await reqAssginRoles(dataRole)
  console.log(res)
  // 关闭抽屉
  drawerRole.value = false
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '分配职务成功',
    })
    getUserList(currentPage.value)
  }
}
// 批量删除
// 1. 收集复选框
const handleSelectionChange = (value: any) => {
  //   console.log(value)
  selectionArr.value = value
}
// 2. 请求删除
const batchDelete = async () => {
  let idArr: any = []
  selectionArr.value.forEach((item: any) => idArr.push(item.id))
  console.log(idArr)
  let res: any = await reqBatchDeleteUser(idArr)
  console.log(res)
  if (res.code === 200) {
    getUserList()
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
// 删除按钮
const deleteUser = async (row: User) => {
  let res: any = await reqDeleteUser(row.id as number)
  if (res.code === 200) {
    let page =
      userList.value.length > 1 ? currentPage.value : currentPage.value - 1
    getUserList(page)
    ElMessage({
      type: 'success',
      message: '操作陈工',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
//  编辑按钮
const editUser = (row: User) => {
  Object.assign(addUserParams, row)
  drawer.value = true
  nextTick(() => {
    addUserForm.value.clearValidate()
  })
}
const addFlag = () => {
  // 此处考虑拿不到 表单实例的情况
  drawer.value = true
  addUserParams.id = 0
  nextTick(() => {
    addUserForm.value.resetFields()
  })
}
// 搜索功能实现
const searchUser = async () => {
  // 问题：如何获取所有用户遍历
  // 传 total 值
  let res: UserResponseData = await reqAllUser(1, total.value)
  console.log(res)
  if (res.code === 200) {
    userList.value = res.data.records.filter(
      (item) => item.username === userName.value,
    )
    console.log(userList.value)
  } else {
    ElMessage({
      type: 'error',
      message: '查询失败',
    })
  }
}
// 重置功能实现
const reset = () => {
  // 确认重置范围
  // userName.value = ''
  // getUserList()
  // 更简单的思路：调用 页面重置按钮的方法
  layoutStore.refresh = !layoutStore.refresh
}
// 添加用户功能实现
// 1. 绑定数据  并确认
// 2. 数据校验
// 3. 发送请求 且包含统一校验
const validateName = (rule: any, value: any, callback: any) => {
  // 长度校验
  if (value.trim().length < 5) {
    callback(new Error('用户名至少 5 位'))
  } else if (/^\d+$/.test(value.trim())) {
    callback(new Error('非法用户名，请至少包含一位字母'))
  } else {
    callback()
  }
}
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length < 5) {
    callback(new Error('用户昵称至少 5 位'))
  } else {
    callback()
  }
}
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length < 6) {
    callback(new Error('用户密码至少 6 位'))
  } else {
    callback()
  }
}
const addUserRules = {
  name: [{ required: true, validator: validateName, trigger: 'blur' }],
  username: [{ required: true, validator: validateUsername, trigger: 'blur' }],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
}

const addOrUpdateUser = async () => {
  // 1. 对表单进行完整的校验
  await addUserForm.value.validate()
  // 2. 发送请求  添加用户
  let res: any = await reqAddOrUpdUser(addUserParams)
  drawer.value = false
  if (res.code === 200) {
    getUserList()
    ElMessage({
      type: 'success',
      message: addUserParams.id ? '更新成功' : '添加成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: addUserParams.id ? '更新失败' : '添加失败',
    })
  }
}
onMounted(() => {
  getUserList()
})
</script>

<style scoped lang="scss">
.container_header {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.demo-drawer__footer {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: end;
}
</style>
